<!-- 搜索多选标签组件 -->
<!-- 远程搜索可加 remote
  :remote-method="querySearch"-->
<!-- 搜索接口返回格式 searchList格式[{id: '', value: ''}] -->
<template>
  <div>
    <el-select
      v-if="isRemote"
      v-model="selectValue"
      multiple
      filterable
      remote
      :remote-method="querySearch"
      reserve-keyword
      placeholder="请输入关键词"
      :loading="loading"
    >
      <el-option
        v-for="item in searchList"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
    <el-select
      v-if="!isRemote"
      v-model="selectValue"
      multiple
      filterable
      reserve-keyword
      placeholder="请输入关键词"
      :loading="loading"
    >
      <el-option
        v-for="item in searchList"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CommonAutocompleteTag',
  props: {
    searchUrl: {
      type: String,
      default: ''
    },
    tagData: {
      type: Array,
      default: () => []
    },
    isRemote: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      loading: false,
      inputVisible: false,
      selectValue: '',
      searchList: []
    }
  },
  watch: {
    searchUrl: function(val) {
      if (val) {
        this.searchUrl = val;
      }
    },
    tagData: function(val) {
      if (val) {
        this.selectValue = val;
      } else {
        this.selectValue = '';
      }
    },
    selectValue: function(val) {
      this.$emit('change', val);
    }
  },
  mounted: function() {
    this.initSearchData();
  },
  methods: {
    querySearch(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          request({
            url: this.searchUrl,
            method: 'get',
            params: {
              name: query
            }
          }).then(res => {
            this.loading = false;
            this.searchList = res.data;
            this.searchList = this.searchList.map(item => item.value);
            this.searchList = this.searchList.filter(item => {
              return item.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            });
          });
        }, 200);
      } else {
        this.initSearchData();
      }
    },
    initSearchData() {
      request({
        url: this.searchUrl,
        method: 'get',
        params: {
          name: ''
        }
      }).then(res => {
        this.searchList = res.data;
        this.searchList = this.searchList.map(item => item.value);
      });
    }
  }
}
</script>
<style>
</style>
